package com.flexdms.jsfutils;

import java.io.IOException;
import java.util.logging.Logger;

import javax.el.VariableMapper;
import javax.faces.application.Resource;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.view.facelets.FaceletContext;
import javax.faces.view.facelets.TagAttribute;
import javax.faces.view.facelets.TagAttributeException;
import javax.faces.view.facelets.TagConfig;
import javax.faces.view.facelets.TagHandler;

import com.sun.faces.facelets.el.VariableMapperWrapper;

public class IncludeTagHandler extends TagHandler
{
	protected final TagAttribute src;
	public static final Logger logger=Logger.getLogger(IncludeTagHandler.class.getName());


	public IncludeTagHandler(TagConfig config)
	{
		super(config);
		this.src = this.getAttribute("src");
	}

	public void apply(FaceletContext ctx, UIComponent parent)
			throws IOException
	{
		
		String src = this.src.getValue(ctx);
		FacesContext fc = FacesContext.getCurrentInstance();
		Resource res=fc.getApplication().getResourceHandler().createResource(src);
		if (res==null)
		{
			logger.warning("Resource "+src+" does not exist");
			return;
		}
		VariableMapper orig = ctx.getVariableMapper();
		ctx.setVariableMapper(new VariableMapperWrapper(orig));
		try
		{
			ctx.includeFacelet(parent, res.getURL());
		} catch (IOException e)
		{
			throw new TagAttributeException(this.tag, this.src,
					"Invalid resource : " + src);
		} finally
		{
			ctx.setVariableMapper(orig);
		}
	}

}